package fojta;

import java.util.*;


// TODO complete rewrite and use Resistor instead of multiresistor
public class CalculateResistance {
	
	private ResistorPoint plus  = new ResistorPoint();
	private ResistorPoint minus = new ResistorPoint();
	
	public CalculateResistance() {
		initResistor(1);
	}
	
	public CalculateResistance(float resistance) {
		initResistor(resistance);
	}
	
	public ResistorPoint getPlus() {
		return plus;
	}
	public void setPlus(ResistorPoint plus) {
		this.plus = plus;
	}
	public ResistorPoint getMinus() {
		return minus;
	}
	public void setMinus(ResistorPoint minus) {
		this.minus = minus;
	}
	
	/**
	 * create connections between plus and minus poles
	 * set one connections to resistance and second to half
	 * @param resistance
	 */
	public void initResistor( float resistance ) {
		/*
		plus.setLeft (minus);
		plus.setRight(minus);
		plus.getLeftResistor().setResistance(resistance);
		plus.getRightResistor().setResistance(resistance/2);
		*/
		plus.makeLeft().setLeft(minus);
		plus.getLeftResistor().setResistance(resistance);
		minus.getRightResistor().setResistance(resistance/2);
		
	}
	
	public float calculate() {
		ResistorPoint R = null;
		boolean visited[] = new boolean[100];
		float resistance = 0;
		// visited[minus.getId()] = true;

		Stack<ResistorPoint> stack = new Stack<ResistorPoint>();

		stack.push(plus);
		/*
		 * We use deep search
		 */
		// pop
		while( ! stack.isEmpty() ) {
			
			R = (ResistorPoint) stack.pop();
			visited[R.getId()] = true;
			
			// there can be more than 4 directions.
			for(Directions d :
				Directions.values() )
			{
				ResistorPoint next = R.getDir(d);  
				if( next != null && 
					! visited[ next.getId() ] ) {
					stack.push(next);
					resistance += R.getResistance(d.getId());
				}
			}
			
		}
		
		return resistance;
	}

}
